//
//  CertKeyIdentifier.m
//  TestProject
//
//  Created by 武侠 on 2022/2/17.
//  Copyright © 2022 zhulong. All rights reserved.
//

#import "CertKeyIdentifier.h"
#import "CertTLV.h"
#import "CertItemLength.h"

@implementation CertKeyIdentifier

/*
 30 1F(31):
     06 03(03): 55 1D 23     (2.5.29.35)
     04 18(24):
         30 16(22):          (bea67e4d3d7c8fa055e6c12f092e2c2043b3427f)
             80 14(20): BE A6 7E 4D 3D 7C 8F A0 55 E6 C1 2F 09 2E 2C 20 43 B3 42 7F
 */

- (NSDictionary<NSNumber *,NSString *> *)objectType {
    return @{
        @(0x80) : @"keyIdentifier",
        @(0xa1) : @"authorityCertIssuer",
        @(0x82) : @"authorityCertSerialNumber",
    };
}

+ (BOOL)isValid:(NSData *)data {
    if ([super isValid:data] == NO) {
        return NO;
    }
    char *sdata = (char *)data.bytes;
    return (uint8_t)sdata[0] == 0x30;
}

- (id)getObject:(NSData *)data type:(uint16_t)type {
    char *sdata = (char *)data.bytes;
    CertItemLength *length = [[CertItemLength alloc] initWithData:sdata index:1];
    
    if (type == 0x80 || type == 0x82) {
        return [CertTLV octetStringFromValue:sdata begin:0 length:length];
    } else if (type == 0xa1) {
        return [[CertGeneralName alloc] initWithData:data];
    }
    return [super getObject:data type:type];
}

- (NSString *)description {
    NSMutableString *str = [NSMutableString string];
    if (self.keyIdentifier != nil && self.keyIdentifier.length > 0) {
        [str appendFormat:@"KeyIdentifier(密钥标识符): %@\n", self.keyIdentifier];
    }
    if (self.authorityCertIssuer != nil ) {
        NSString *issuer = [self.authorityCertIssuer.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"];
        [str appendFormat:@"AuthorityCertIssuer(授权证书颁发者): \n[\n\t%@\n]\n", issuer];
    }
    if (self.authorityCertSerialNumber != nil && self.authorityCertSerialNumber.length > 0) {
        [str appendFormat:@"AuthorityCertSerialNumber(授权证书序列号): %@\n", self.authorityCertSerialNumber];
    }
    if (str.length > 0) {
        [str deleteCharactersInRange:NSMakeRange(str.length-1, 1)];
    }
    return str;
}

@end
